package com.tfswx.ruleengine.compute.gzjy;

import com.tfswx.ruleengine.compute.exception.AppException;

import java.util.Map;

/**
 * @author ricky
 * @date 2021/11/1
 */
public class DatabaseClassLoader<T> extends ClassLoader {
    private final Map<String, byte[]> datas;
    private final Class<T> interfaceClass;

    public DatabaseClassLoader(Class<T> interfaceClass, Map<String, byte[]> datas) {
        super(interfaceClass.getClassLoader());
        this.datas = datas;
        this.interfaceClass = interfaceClass;
    }

    @Override
    public Class<?> findClass(String name) {
        byte[] data = datas.get(name);
        return defineClass(name, data, 0, data.length);
    }

    public T getInstance(String className) {
        try {
            Class<?> cl = loadClass(className);
            Class<? extends T> c = cl.asSubclass(interfaceClass);
            return c.newInstance();
        } catch (Exception e) {
            throw new AppException("获取实例【" + className + "】失败：" + e.getMessage(), e);
        }
    }
}
